const Service = require("egg").Service;
const fs = require("fs");
const path = require("path");
const md5 = require("md5");
const fse = require("fs-extra");
const awaitWriteStream = require("await-stream-ready").write;
const { emptyDirSync, mkdirpSync } = fse;

class UtilsService extends Service {
  // 获取视频列表
  async uploadFiles() {
    const { ctx } = this;
    try {
      const stream = await ctx.getFileStream();
      const filename =
        md5(stream.filename) +
        path.extname(stream.filename).toLocaleLowerCase();
      const localFilePath = path.join(
        __dirname,
        `../public/uploads/`,
        filename
      );
      const writeStream = fs.createWriteStream(localFilePath);
      await awaitWriteStream(stream.pipe(writeStream));
      const fileUrl = this.ctx.origin + `/public/uploads/` + filename;
      return fileUrl;
    } catch (error) {
      throw new Error(err)
    }
  }
}

module.exports = UtilsService;
